package com.example.weight.greenSeasons.SolidLiquid;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;
import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.AuthFailureError;
import com.android.volley.DefaultRetryPolicy;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.example.weight.R;
import com.example.weight.config.Config;
import com.hjq.bar.OnTitleBarListener;
import com.hjq.bar.TitleBar;

import org.json.JSONException;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

public class Gongyixianchang extends AppCompatActivity {

    private TitleBar titleBar;
    //日期
    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");// HH:mm:ss
    Date incomingDate = new Date(System.currentTimeMillis());
    Calendar calendar= Calendar.getInstance(Locale.CHINA);
    private TextView worm_incoming_incomeDate;
    //表读数
    private EditText shashuifenliqi,guyefenlizha,qingyunliang;
    //备注
    private EditText remark;
    //用户、抄表人
    private String name,factory;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_solidliquid_gongyixianchang_table);

        //页面返回按钮
        titleBar=findViewById(R.id.titleBar);
        titleBar.setOnTitleBarListener(new OnTitleBarListener() {
            @Override
            public void onLeftClick(View v) {
                Gongyixianchang.this.finish();
            }
            @Override
            public void onTitleClick(View v) {
            }
            @Override
            public void onRightClick(View v) {
            }
        });


        //日期
        worm_incoming_incomeDate = findViewById(R.id.incomeDate);
        worm_incoming_incomeDate.setText(simpleDateFormat.format(incomingDate));

        shashuifenliqi = findViewById(R.id.shashuifenliqi);
        guyefenlizha = findViewById(R.id.guyefenlizha);
        qingyunliang = findViewById(R.id.qingyunliang);
        remark = findViewById(R.id.et_remarks);

        //用户
        Intent previousIntent = getIntent();
        name = previousIntent.getStringExtra("name");
        factory = previousIntent.getStringExtra("factory");
        //获取当天最新一条数据
        RequestQueue queue = Volley.newRequestQueue(this);
        String url = Config.url + "/sjq/sjqSolidliquidProcess/getlast" + "?factory=" + factory;
        StringRequest stringRequest = new StringRequest(Request.Method.GET, url,
                new Response.Listener<String>() {
                    @Override
                    public void onResponse(String response) {
                        try {
                            JSONObject jsonObject = new JSONObject(response);
                            JSONObject data = jsonObject.getJSONObject("data");
                            Log.d("sr",data.toString());
                            if (!data.isNull("id") && data.getString("factory").equals(factory)) {
                                shashuifenliqi.setHint(data.getString("sandProduction"));
                                guyefenlizha.setHint(data.getString("trainNumber"));
                                qingyunliang.setHint(data.getString("clearanceVolume"));
                                remark.setHint(data.getString("remark"));
                                Toast.makeText(Gongyixianchang.this,
                                        "今日已填写此表", Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Toast.makeText(Gongyixianchang.this,
                        "获取信息失败 " + error.getMessage(), Toast.LENGTH_SHORT).show();
            }
        });
        stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
        queue.add(stringRequest);
    }

//    选择日期
    @SuppressLint({"DefaultLocale", "ResourceType"})
    public void selectDate(View view){
        int YEAR = calendar.get(Calendar.YEAR);
        int MONTH = calendar.get(Calendar.MONTH);
        int DAY = calendar.get(Calendar.DAY_OF_MONTH);
        new DatePickerDialog(this, 2, (view1, year, month, day) -> {
            // 更新EditText控件日期 小于10加0
            worm_incoming_incomeDate.setText(new StringBuilder()
                    .append(year)
                    .append("-")
                    .append((month + 1) < 10 ? "0"+ (month + 1) : (month + 1))
                    .append("-")
                    .append((day < 10) ? "0" + day : day));
            },YEAR, MONTH, DAY).show();
    }
    //提交按钮
    public void save(View view) {
        if (shashuifenliqi.getText().toString().equals("")) {
            Toast.makeText(this, "请填写砂水分离器出砂量", Toast.LENGTH_SHORT).show();
            return;
        }
        if (guyefenlizha.getText().toString().equals("")) {
            Toast.makeText(this, "请填写固液分离渣清运车次", Toast.LENGTH_SHORT).show();
            return;
        }
        if (qingyunliang.getText().toString().equals("")) {
            Toast.makeText(this, "请填写固液分离渣清运量", Toast.LENGTH_SHORT).show();
            return;
        }
        new AlertDialog.Builder(this)
                .setTitle("确定保存吗？")
                .setCancelable(false)
                .setNegativeButton("取消", ((dialog, which) ->
                        Toast.makeText(this, "取消保存", Toast.LENGTH_SHORT).show()))
                .setPositiveButton("确定", (dialog, which) -> {
                    //提交请求
                    RequestQueue queue = Volley.newRequestQueue(this);
                    String url = Config.url + "/sjq/sjqSolidliquidProcess/add";
                    StringRequest stringRequest = new StringRequest(Request.Method.POST, url,
                            new Response.Listener<String>() {
                                @Override
                                public void onResponse(String response) {
                                    Toast.makeText(Gongyixianchang.this, "保存成功", Toast.LENGTH_SHORT).show();
                                    Log.d("jy", response);
                                    try {
                                        JSONObject jsonObject = new JSONObject(response);
                                        String code = jsonObject.getString("code");

                                        if (code.startsWith("2"))
                                            Toast.makeText(Gongyixianchang.this,
                                                    "保存成功", Toast.LENGTH_SHORT).show();
                                        else
                                            Toast.makeText(Gongyixianchang.this,
                                                    "保存失败", Toast.LENGTH_SHORT).show();
                                    } catch (JSONException e) {
                                        e.printStackTrace();
                                    }
                                }
                            }, new Response.ErrorListener() {
                        @Override
                        public void onErrorResponse(VolleyError error) {
                            Toast.makeText(Gongyixianchang.this,
                                    "保存失败" + error.getMessage(), Toast.LENGTH_SHORT).show();
                        }
                    }) {
                        @Override
                        protected Map<String, String> getParams() throws AuthFailureError {
                            Map<String, String> map=new HashMap<>();
                            map.put("date", worm_incoming_incomeDate.getText().toString());
                            map.put("sand_production", shashuifenliqi.getText().toString());
                            map.put("train_number", guyefenlizha.getText().toString());
                            map.put("clearance_volume", qingyunliang.getText().toString());
                            map.put("reader",name);
                            map.put("remarks", remark.getText().toString());
                            map.put("factory", factory);
                            return map;
                        }
                    };
                    stringRequest.setRetryPolicy(new DefaultRetryPolicy(10 * 1000,
                            DefaultRetryPolicy.DEFAULT_MAX_RETRIES, DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
                    queue.add(stringRequest);
                })
                .show();
    }
}